package com.white.controller;

import com.white.bean.Article;
import com.white.bean.Reward;
import com.white.bean.User;
import com.white.service.ArticleService;
import com.white.service.RewardService;
import com.white.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class RewardController {

    @Autowired
    UserService userService;
    @Autowired
    RewardService rewardService;

    @Autowired
    ArticleService articleService;

    /**
     * 打赏
     * @param userId 打赏用户id
     * @param articleId 打赏的文章id
     * @param money 打赏金额
     * @param remark 留言
     */
    @PostMapping("/reward")
    @ResponseBody
    @Transactional
    public boolean reward(@CookieValue(UserController.LOGIN_USER_ID) Long userId,
                       @RequestParam("articleId") Long articleId,
                       @RequestParam("money") double money,
                       @RequestParam("remark") String remark) {
        /*检查账户余额*/
        User user = userService.getById(userId);
        if (user.getBalance() < money) {
            return false;
        }
        user.setBalance(user.getBalance() - money);
        userService.updateById(user);
        Article article = articleService.getByArticleId(articleId);
        User beRewardUser = userService.getById(article.getUserId());
        beRewardUser.setBalance(beRewardUser.getBalance() + money);
        userService.updateById(beRewardUser);
        Reward reward = new Reward(userId, articleId, money, remark);
        rewardService.save(reward);
        return true;
    }
}
